package com.example.auction.fragment;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.auction.R;
import com.example.auction.adapter.PublishedItemListAdapter;
import com.example.auction.bean.Item;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyUtil;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


public class TabLayoutPublishedItemFragment extends Fragment {

    //分类商品展示
    private ListView lv_published_item_list;
    private TextView tv_list_none;

    //数据源的列表的类型是Map类型（键值对），Map<String（键名），Object（值的类型）>
    private List<Item> publishedItemList;

    private Integer user_id;
    private Integer item_id;
    private Sqlite sqlite;
    private Cursor cursor;

    //类别名字
    private String published;

    //是否第一次加载
    private boolean isFirstLoading = true;

    /**
     * 在fragment可见的时候，刷新数据
     */
    @Override
    public void onResume() {
        super.onResume();

        if (!isFirstLoading) {
            //如果不是第一次加载，刷新数据
            initData();
            inAdapter();
        }

        isFirstLoading = false;
    }


    public TabLayoutPublishedItemFragment() {

    }

    //接受数据的构造方法
    public TabLayoutPublishedItemFragment(Integer userId, String published) {
        this.user_id = userId;
        this.published = published;
//        if (userId != 0 && !published.equals("")) {
//
//        }
    }


    public static TabLayoutPublishedItemFragment newInstance(String param1, String param2) {
        TabLayoutPublishedItemFragment fragment = new TabLayoutPublishedItemFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tab_layout_published_item, container, false);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //fragment中的数据库对象要在onViewCreat中创建（fragment的生命周期）
        sqlite = new Sqlite(getActivity());
        lv_published_item_list = view.findViewById(R.id.lv_published_item_list);
        tv_list_none = view.findViewById(R.id.tv_list_none);

        //初始化数据
        initData();
        inAdapter();
    }

    private void inAdapter() {
        //初始化适配器
        PublishedItemListAdapter publishedItemListAdapter = new PublishedItemListAdapter(
                getActivity(), publishedItemList, user_id, published
        );

        //装载适配器
        lv_published_item_list.setAdapter(publishedItemListAdapter);
    }

    @SuppressLint("Range")
    private void initData() {
        //已完成的拍卖品列表
        publishedItemList = new ArrayList<>();

        //分开我买到的和我卖出的物品查询
        if (published.equals("我发布的")) {
            cursor = sqlite.selectItem("owner_id", user_id.toString(),
                    "owner_visible", 1, "addtime desc");
//            cursor = sqlite.selectItem("item_id",Integer.valueOf(2).toString(),"item_id desc");
        } else if (published.equals("有人出价")) {
            cursor = sqlite.selectBidItem(
                    user_id.toString(), "0", "endtime desc");
        }

        if (cursor.getCount() > 0) {
/*
            //[1]显示
            View对象.setVisibility(View.VISIBLE);
            //[2]隐藏 但是会占据到空间的大小
            View对象.setVisibility(View.INVISIBLE);
            //[3]隐藏 但是不会占据空间的大小
            View对象.setVisibility(View.GONE);
*/
            tv_list_none.setVisibility(View.GONE);
        } else {
            tv_list_none.setVisibility(View.VISIBLE);
        }

        while (cursor.moveToNext()) {

            Item item = new Item();

            //根据id获取前图片
            byte[] image = cursor.getBlob(cursor.getColumnIndex("item_image"));

            //物品名
            String itemName = cursor.getString(cursor.getColumnIndex("item_name"));
            //描述
            String itemDes = cursor.getString(cursor.getColumnIndex("item_desc"));
            //价格
            String maxPrice = cursor.getString(cursor.getColumnIndex("max_price"));
            //发布者名字
            Integer owner_id = 0;
            owner_id = cursor.getInt(cursor.getColumnIndex("owner_id"));

            Integer winner_id = cursor.getInt(cursor.getColumnIndex("winner_id"));

            String ownerName = MyUtil.getUserNameByID(getActivity(), owner_id);
            //截止时间
            String endTime = cursor.getString(cursor.getColumnIndex("endtime"));

            Integer owner_visible = cursor.getInt(cursor.getColumnIndex("owner_visible"));
            //状态
            String state = cursor.getString(cursor.getColumnIndex("state"));

            item_id = cursor.getInt(cursor.getColumnIndex("item_id"));

            //数据用javabean存储
            item.setItemId(item_id);


            item.setWinnerId(winner_id);

            item.setOwnerId(owner_id);

            item.setImage(image);
            item.setItemName(itemName);
            item.setItemDesc(itemDes);
            item.setEndtime(endTime);

            //发布时的最高价等于发布价
            item.setMaxPrice(maxPrice);
            item.setOwnerVisible(owner_visible);
            item.setState(state);

            //将子项加进列表
            publishedItemList.add(item);
        }

    }
}